package net.sf.calibur.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

public class Util {
	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String) {
			return ((String) obj).length() == 0;
		} else if (obj instanceof Collection) {
			return ((Collection<?>) obj).size() == 0;
		} else if (obj instanceof Set) {
			return ((Set<?>) obj).size() == 0;
		} else if (obj instanceof Map) {
			return ((Map<?, ?>) obj).size() == 0;
		} else {
			return Array.getLength(obj) == 0;
		}
	}

	public static String upperFirstLetter(String str) {
		return new StringBuffer().append(str.substring(0, 1).toUpperCase())
				.append(str.substring(1)).toString();
	}
	
	public static String toHex(byte[] bytes) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		int count = bytes.length / 16;
		int reset = bytes.length % 16;
		
		int idx = 0;
		for (int i = 0; i < count; ++i) {
			pw.print(String.format("[%03d - %03d]: ", i * 16, (i + 1) * 16 - 1));
			for (int j = 0; j < 16; ++j, ++idx) {
				if (j == 8) {
					pw.print("- ");
				}
				
				pw.print(String.format("%02X ", bytes[idx]));
			}
			pw.println();
		}
		
		pw.print(String.format("[%03d - %03d]: ", idx, bytes.length - 1));
		for (int i = 0; i < reset; ++i, ++idx) {
			if (i == 8) {
				pw.print("- ");
			}
			
			pw.print(String.format("%02X ", bytes[idx]));
		}
		
		return sw.toString();
	}
}
